/*
 * @lc app=leetcode.cn id=946 lang=javascript
 *
 * [946] 验证栈序列
 */

// @lc code=start
/**
 * @param {number[]} pushed
 * @param {number[]} popped
 * @return {boolean}
 */
var validateStackSequences = function (pushed, popped) {
  // 出栈元素必然等于当前栈顶元素或者下一个入栈元素
  let stack = [];
  let i = 0;

  for (const n of pushed) {
    stack.push(n);
    while (stack.length && popped[i] === stack[stack.length - 1]) {
      stack.pop();
      i++;
    }
  }

  return !stack.length;
};
// @lc code=end
